//
//  WmcEditWatermarksDBManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/8/2.
//

import UIKit

// MARK: - 扩展WmcUserEditWatermarksDBManager + WmcDBProtocol

extension WmcUserEditWatermarksDBManager: WmcDBProtocol {
    static var tableName: String = "user_edit_watermarks"

    static var dataType: [WmcDBManager.DataType] {
        return [
            .integer(name: "watermark_id"),
            .integer(name: "watermark_json"),
        ]
    }
}

// MARK: - [WmcUserEditWatermarksDBManager]

struct WmcUserEditWatermarksDBManager {
    /// 插入水印数据模型
    /// - Parameters:
    ///   - watermarkModel: 水印模型
    ///   - resultBlock: 结果回调
    static func insertWatermarkModel(_ watermarkModel: WmcWatermarkDetailModel,
                                     resultBlock: YPBlock.OneParam<WmcWatermarkDetailModel>? = nil)
    {
        deleteWatermarkModel(wmId: watermarkModel.wmId, resultBlock: { result in
            guard let json = watermarkModel.toJSONString() else { return }
            // 开始存储
            WmcDBManager.shared.insertData(tableName: tableName, insertData: [
                .init(column: Self.dataType[0], value: watermarkModel.wmId),
                .init(column: Self.dataType[1], value: json),
            ]) { _ in
                resultBlock?(watermarkModel)
            }
        })
    }

    /// 查找水印数据模型
    /// - Parameters:
    ///   - wmId: 水印id
    ///   - resultBlock: 结果回调
    static func searchWatermarkModel(wmId: Int,
                                     resultBlock: @escaping YPBlock.OneParam<WmcWatermarkDetailModel?>)
    {
        WmcDBManager.shared.searchCustomData(tableName: tableName,
                                             condition: "where watermark_id = \"\(wmId)\"") { list in
            if list.count == 1,
               let result = list.first,
               let watermarkJson = result["watermark_json"] as? String,
               let wmcModel = WmcWatermarkDetailModel.deserialize(from: watermarkJson)
            {
                resultBlock(wmcModel)
            }else{
                resultBlock(nil)
            }
        }
    }

    /// 删除水印数据模型
    /// - Parameters:
    ///   - wmId: 水印id
    ///   - resultBlock: 结果回调
    static func deleteWatermarkModel(wmId: Int,
                                     resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        WmcDBManager.shared.deleteCustomData(tableName: tableName,
                                             condition: "where watermark_id = \(wmId)",
                                             resultBlock: resultBlock)
    }
}
